package com.joe.gulishop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.joe.common.constant.ProductConstant;
import com.joe.gulishop.product.dao.AttrAttrgroupRelationDao;
import com.joe.gulishop.product.dao.AttrGroupDao;
import com.joe.gulishop.product.dao.CategoryDao;
import com.joe.gulishop.product.entity.AttrAttrgroupRelationEntity;
import com.joe.gulishop.product.entity.AttrGroupEntity;
import com.joe.gulishop.product.entity.CategoryEntity;
import com.joe.gulishop.product.service.AttrAttrgroupRelationService;
import com.joe.gulishop.product.service.CategoryService;
import com.joe.gulishop.product.vo.AttrResponseVO;
import com.joe.gulishop.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joe.common.utils.PageUtils;
import com.joe.common.utils.Query;

import com.joe.gulishop.product.dao.AttrDao;
import com.joe.gulishop.product.entity.AttrEntity;
import com.joe.gulishop.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.Attr;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
//        首先进行保存数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
//        1.保存基本数据
        this.save(attrEntity);
        //2.保存关联关系因为sale和base使用是同一个保存的方法所以要进行判断1.是基本属性需要保存非组
        //0是销售属性，你没有分组
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }


    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        System.out.println(attrType);
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((wrapper1) -> {
                wrapper1.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
//        AttrResponseVO responseVO=new AttrResponseVO();
        //获取所有的page的中的attrEntity的数据
        List<AttrEntity> records = page.getRecords();

        List<AttrResponseVO> attr_id = records.stream().map((attrEntity -> {
                    AttrResponseVO responseVO = new AttrResponseVO();
                    BeanUtils.copyProperties(attrEntity, responseVO);
                    //查询属性和组的关系。
                    AttrAttrgroupRelationEntity attrAttrgroupRelationEntity =
                            relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                    if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                        responseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
//"catelogName": "手机/数码/手机", //所属分类名字
                    CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                    if (categoryEntity != null && categoryEntity.getName() != null) {
                        responseVO.setCatelogName(categoryEntity.getName());
                    }

                    return responseVO;
                })

        ).collect(Collectors.toList());
        pageUtils.setList(attr_id);


        return pageUtils;


    }

    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        AttrResponseVO attrVo = new AttrResponseVO();
        AttrEntity attrEntity = attrDao.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, attrVo);

        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrVo.setCatelogPath(catelogPath);
        CategoryEntity byId = categoryService.getById(attrEntity.getCatelogId());
        if (byId != null) {
            attrVo.setCatelogName(byId.getName());
        }

        //重新获取文件文件的路径
//        List<Long> catePath=new ArrayList<>();
//        List<Long> parentList = findParentList(catePath, attrEntity.getCatelogId());
//        Collections.reverse(parentList);
//        attrVo.setCatelogPath(parentList.toArray(new Long[parentList.size()]));
        //attrVo.setCatelogPath();
        //attrVo.setGroupName();
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrAttrgroupRelationEntity != null) {
                attrVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }
        }


        return attrVo;
    }

    @Transactional
    @Override
    public void updateAttrById(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
//        先更新属性的数据库，在更细关系的数据库
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {

            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());

            Integer count = Math.toIntExact(relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId())));

            if (count > 0) {
                relationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(attrAttrgroupRelationEntity);
            }
        }


    }

    //根据groupId获取关联关系
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attr_group_id = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId)
        );
        List<Long> list = attr_group_id.stream().map((param) -> {
            return param.getAttrId();
        }).collect(Collectors.toList());
        if (list == null || list.size() == 0) {
            return null;
        } else {
            List<AttrEntity> attrEntityList = attrDao.selectBatchIds(list);
            return attrEntityList;
        }


    }

    //获取所有的未关联的数据
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        //1.关联的数据
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //1.1当前品类的id
        Long catelogId = attrGroupEntity.getCatelogId();
        //2.查询组中没有关联的数据，首先要理解需求，关联的所有分组中没有引用的属性
//        2.0 查询出在关系表中所有关联的数据
        List<AttrGroupEntity> attrgroupIds = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
//        获取所有的组的id
        List<Long> attrgroupList = attrgroupIds.stream().map((attr) -> {
            return attr.getAttrGroupId();
        }).collect(Collectors.toList());
//        2.1获取所有组的所有的属性信息
        List<AttrAttrgroupRelationEntity> attrgroupRelations = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrgroupList));
        //然后获取所有的组中使用到的属性的Id
        List<Long> collect = attrgroupRelations.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
//      2.2  然后筛选出没有使用到的集合展示出来
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (collect!=null && collect.size() > 0) {
            wrapper.notIn("attr_id", collect);
        }
        //3.0开始模糊查询
        String key = (String) params.get("key");
        if (!key.isEmpty()) {
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    public List<Long> findParentList(List<Long> list, Long catelogId) {
        list.add(catelogId);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            // categoryDao.selectById(categoryEntity.getParentCid());
            findParentList(list, categoryEntity.getParentCid());
        }

        return list;
    }


}